package com.sailmi.common.tool.crypto;

import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.util.encoders.Hex;
import java.math.BigInteger;

public class SM2Decryption {

	public static void main(String[] args) {
		String secStrWeb = "9061f70839a8951e68df09a232fd8bd9e93a15fc347eed2371e1abe770a56e0b6986f10bb56c4cccf2c88f559deeb6fcd62ac455c724e248b127940bc7de3ffaea27cda3da321658b62f99c2854f672f9a74f74baf8acbd01044bc42ca7cf4fe0cc211dc78";
		String privateStr = "726ac2141eaf6dcef4d279597fd21720d5f79ccefe9ebd7cd6cd5fdff9ab0c2d";

		try {
			String decrypted = decryptSM2(secStrWeb, privateStr);
			System.out.println("解密结果: " + decrypted);
		} catch (Exception e) {
			System.err.println("解密失败: " + e.getMessage());
			e.printStackTrace();
		}
	}
	public static String decryptSM2(String encryptedHex, String privateKeyHex) throws Exception {
		// 添加04前缀（如果不存在）
		if (!encryptedHex.startsWith("04")) {
			encryptedHex = "04" + encryptedHex;
		}

		// 1. 获取SM2曲线参数
		ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("sm2p256v1");
		ECDomainParameters domainParams = new ECDomainParameters(
			spec.getCurve(), spec.getG(), spec.getN(), spec.getH());

		// 2. 准备私钥
		BigInteger privateKeyInt = new BigInteger(privateKeyHex, 16);
		ECPrivateKeyParameters privateKeyParams = new ECPrivateKeyParameters(privateKeyInt, domainParams);

		// 3. 初始化SM2引擎 (使用C1C3C2模式)
		SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
		engine.init(false, privateKeyParams);

		// 4. 解码密文
		byte[] encryptedData = Hex.decode(encryptedHex);

		// 5. 解密
		byte[] decrypted = engine.processBlock(encryptedData, 0, encryptedData.length);

		return new String(decrypted, "UTF-8");
	}
}
